#include "byte_stream.hh"

// Dummy implementation of a flow-controlled in-memory byte stream.

// For Lab 0, please replace with a real implementation that passes the
// automated checks run by `make check_lab0`.

// You will need to add private members to the class declaration in `byte_stream.hh`

using namespace std;

ByteStream::ByteStream(const size_t capacity): _capacity(capacity) {}

size_t ByteStream::write(const string &data) {
    // 最多能写入多少
    int len_write = min(data.size(), remaining_capacity());
    _byte_written += len_write;
    for (int i = 0; i < len_write; i++)
        q.push_back(data[i]);
    return len_write;
}

//! \param[in] len bytes will be copied from the output side of the buffer
string ByteStream::peek_output(const size_t len) const {
    int len_peek = min(len, buffer_size());
    return string().assign(q.begin(), q.begin() + len_peek);
}

//! \param[in] len bytes will be removed from the output side of the buffer
void ByteStream::pop_output(const size_t len) { 
    int len_pop = min(len, buffer_size());
    for (int i = 0; i < len_pop; i++)
        q.pop_front();
    _byte_read += len_pop;
    if (buffer_empty() && input_ended()) 
        _eof = true;
 }

//! Read (i.e., copy and then pop) the next "len" bytes of the stream
//! \param[in] len bytes will be popped and returned
//! \returns a string
std::string ByteStream::read(const size_t len) {
    string str = peek_output(len);
    pop_output(len);
    return str;
}

void ByteStream::end_input() {
    if (buffer_empty())
        _eof = true;
    _input_eof = true;
}

bool ByteStream::input_ended() const { 
    return _input_eof;
}

size_t ByteStream::buffer_size() const {
    return q.size();    
}

bool ByteStream::buffer_empty() const { 
    return q.empty();
}

bool ByteStream::eof() const { 
    return _eof;
}

size_t ByteStream::bytes_written() const { 
    return _byte_written;
}

size_t ByteStream::bytes_read() const { 
    return _byte_read;    
}

size_t ByteStream::remaining_capacity() const { 
    return _capacity - q.size(); 
}
